<template>
    <el-dialog class="upload-work" draggable align-center :title="dialogTile" v-model="dialogVisible" @close="closeDialog"
        width="800">

        <el-form :model="userForm" :rules="userRules" ref="userFormRef">

            <el-form-item label="作品名称：" label-width="120" prop="workName" required>
                <el-input v-model="userForm.workName" placeholder="请输入作品名称" :maxlength="50" :show-word-limit="true" />
            </el-form-item>
            <el-form-item label="作品描述：" label-width="120" prop="workDescription">
                <el-input v-model="textDes" @click="openEditorDialog" readonly placeholder="请输入内容" :maxlength="1000"
                    :show-word-limit="true" />
            </el-form-item>
            <el-form-item label="作品封面：" label-width="120" prop="workCouerPath">
                <el-upload ref="uploadPic" class="avatar-uploader" :action="uploadFileUrl" methods="post"
                    :before-upload="beforePicUpload" :on-preview="handlePreview" :on-success="handleSuccess"
                    :on-error="handleError" :limit="1" :on-exceed="handlePicExceed" :auto-upload="false"
                    :file-list="picFileList" list-type="picture-card" :headers="{
                        'Authorization': 'Bearer ' + token
                    }">
                    <template #trigger>
                        <el-button size="small" type="primary">选择文件</el-button>
                    </template>
                    <el-button type="success" class="submit-bt" @click="submitUpload(1)">点击上传</el-button>
                </el-upload>
            </el-form-item>
            <el-form-item label="作品文件：" label-width="120" prop="workPath">
                <el-upload ref="uploadFile" class="upload-demo" :action="uploadFileUrl" methods="post"
                    :before-upload="beforeUpload" :on-success="handleSuccess" :on-error="handleError" :limit="1"
                    :on-exceed="handleExceed" :file-list="fileList" list-type="text" :auto-upload="false" :headers="{
                        'Authorization': 'Bearer ' + token
                    }">
                    <template #trigger>
                        <el-button type="primary">选择文件</el-button>
                    </template>
                    <el-button class="submit-bt" type="success" @click="submitUpload(2)">点击上传</el-button>
                </el-upload>
            </el-form-item>
            <video :src="userForm.workPath" v-if="userForm.workPath" class="video" controls></video>
        </el-form>
        <TextEditor ref="textEditor" @give-values="handleDes"></TextEditor>
        <template #footer>
            <el-button @click="closeDialog">取消</el-button>
            <el-button type="primary" @click="saveWork(userFormRef)">保存</el-button>
        </template>
    </el-dialog>
    <el-dialog v-model="picDialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
</template>
<script setup>
import { ref } from 'vue';
import { PostWork, uploadFileUrl, GetWorkDetail } from '@/api/front/contest'
import { ElMessage, genFileId } from 'element-plus';
import store from '@/store';
import TextEditor from './TextEditor.vue'

const emits = defineEmits(['refresh'])

const textEditor = ref(null)
const handleDes = (data) => {
    console.log(data)
    userForm.value.workDescription = data.html
    textDes.value = data.text
}
const openEditorDialog = () => {
    textEditor.value.openDialog(userForm.value.workDescription)
}

const userInfo = store.state.userInfo
const dialogVisible = ref(false)
const picDialogVisible = ref(false)
const dialogImageUrl = ref('')
const dialogTile = ref('')
const uploadPic = ref('')
const uploadFile = ref('')
const token = window.localStorage.getItem('userInfo').token
const userFormRef = ref()
const textDes = ref('')

const userForm = ref(
    {
        workId: null,
        contestId: 0,
        workType: null,
        publisherId: userInfo.userId,
        workName: '',
        workDescription: '',
        workCouerPath: '',
        workPath: '',
        workStatus: 1
    }
)
// userForm.value.workDescription = textEditor.value.editorRef.getHtml()
// 定义form表单的验证规则
const userRules = ref({
    // 作品验证规则
    workName: [
        { required: true, message: '请输入作品名称', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    workDescription: [
        { required: true, message: '请输入作品描述', trigger: 'blur' },
        { min: 1, max: 1000, message: '长度在 1 到 1000 个字符', trigger: 'blur' }
    ],
    workType: [
        { required: true, message: '请选择作品类型', trigger: 'change' }
    ],
    workCouerPath: [
        { required: true, message: '请上传作品封面', trigger: 'change' }
    ],
    workPath: [
        { required: true, message: '请上传作品文件', trigger: 'change' }
    ]

})
const picFileList = ref([])
const fileList = ref([])

const openDialog = async (id, type, workId) => {
    console.log("upid", id, workId)
    dialogVisible.value = true
    userForm.value.contestId = id
    userForm.value.workType = type
    if (workId) {
        dialogTile.value = '修改作品'
        // 获取作品信息
        const res = await GetWorkDetail({ workId: workId })
        console.log(res)
        userForm.value.workId = res.data[0].workId
        userForm.value.workName = res.data[0].workName
        userForm.value.workDescription = res.data[0].workDescription
        userForm.value.workCouerPath = res.data[0].workCouerPath
        picFileList.value = [{
            name: 'workPic.jpeg',
            url: res.data[0].workCouerPath
        }]
        userForm.value.workPath = res.data[0].workPath
        fileList.value = [{
            name: 'workVideo',
            url: res.data[0].workPath
        }]
        textEditor.value.setHtml(res.data[0].workDescription)
        textDes.value = handleHtmlToText(res.data[0].workDescription)
        console.log("userForm.value", userForm.value)

    } else {
        dialogTile.value = '上传作品'
    }
}
const handleHtmlToText = (html) => {
    const div = document.createElement('div')
    div.innerHTML = html
    return div.innerText
}

const closeDialog = () => {
    dialogVisible.value = false
    // 初始化表单
    userForm.value = {
        workId: null,
        contestId: 0,
        workType: null,
        publisherId: userInfo.userId,
        workName: '',
        workDescription: '',
        workCouerPath: '',
        workPath: '',
        workStatus: 1
    }
    picFileList.value = []
    fileList.value = []
    textDes.value = ''

}

const beforePicUpload = (file) => {
    const isJPG = file.type === 'image/jpeg'
    const isPNG = file.type === 'image/png'
    const isLt3M = file.size / 1024 / 1024 < 3
    if (!isJPG && !isPNG) {
        ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!')
        return false
    }
    if (!isLt3M) {
        ElMessage.error('上传头像图片大小不能超过 3MB!')
        return false
    }
    return true
}
const beforeUpload = (file) => {
    // 视频格式
    const isMp4 = file.type === 'video/mp4'
    const isOgg = file.type === 'video/ogg'
    const isWebm = file.type === 'video/webm'
    if (!isMp4 && !isOgg && !isWebm) {
        ElMessage.error('上传视频只能是 MP4、Ogg、Webm 格式!')
        return false
    }
    // 视频大小
    const isLt500M = file.size / 1024 / 1024 < 500
    if (!isLt500M) {
        ElMessage.error('上传视频大小不能超过 500MB!')
        return false
    }
    return true

}

const handlePreview = (file) => {
    console.log(file)
    dialogImageUrl.value = file.url
    picDialogVisible.value = true
}
const handleError = (err) => {
    console.log(err)
}
const handlePicExceed = (files) => {
    // 用JS写upload.value!.clearFiles()
    uploadPic.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    uploadPic.value.handleStart(file)

}
const handleExceed = (files) => {
    // 用JS写upload.value!.clearFiles()
    uploadFile.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    uploadFile.value.handleStart(file)

}
const handleSuccess = (res, file) => {
    // console.log(res)
    // console.log(file)
    if (file.status == 'success') {
        ElMessage.success('上传成功')
        if (file.raw.type == 'image/png' || file.raw.type == 'image/jpeg') {
            userForm.value.workCouerPath = res
        } else {
            userForm.value.workPath = res
        }
    }
    console.log(userForm.value)
}
const submitUpload = (type) => {
    if (type == 1) {
        uploadPic.value.submit()
    } else {
        uploadFile.value.submit()
    }
}

const saveWork = async (formRef) => {
    if (!formRef) {
        return
    }
    await formRef.validate(async (valid, fields) => {
        if (valid) {
            console.log('submit!');
            // 上传作品
            console.log(userForm.value)
            const res = await PostWork(userForm.value)
            console.log(res)
            if (res.data == '添加/修改成功') {
                ElMessage.success('上传成功')
                emits('refresh')
                closeDialog()
            } else {
                ElMessage.error('上传失败')
            }
        } else {
            console.log('error submit!', fields);
        }
    });

}

defineExpose({
    openDialog
})
</script>
<style lang="scss" scoped>
.upload-work {
    .submit-bt {
        margin-left: 10px;
        float: inline-end;
        // height: 30px;
        // width: 70px;
        // font-size: 12px;
        // font-weight: normal;
        // border-radius: 5px;
    }

    .video {
        width: 100%;
        height: 300px;
    }
}
</style>